package com.ys.web.mobao.job;

import com.alibaba.fastjson.JSONObject;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.mobao.MobaoPay;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import com.ys.web.goods.order.service.OrderService;
import com.ys.web.pay.PayEnum;
import com.ys.web.pay.PayService;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.PayOrder;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 支付订单超时处理
 * 每10秒跑一次，找到2分钟前的未支付订单，去支付公司查询该笔订单状态，更新订单信息
 */
@Component
public class MobaoRechargeTimeOut implements Job {
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<PayOrder> list = payService.getPayOrderListByTime();
        list.forEach(payOrder->{
            try{
                JSONObject jsonObject = MobaoPay.tradeStatusQuery(payOrder.getOrderNo());
                String status = jsonObject.getString("orderStatus");
                //支付成功
                switch (status) {
                    case "00":
                        payOrder.setSerialNumber(jsonObject.getString("orderNo"));
                        if (payOrder.getPayStatus().equals(PayEnum.PayStatus.NO_PAY.getCode())) {
                            // 修改支付状态
                            payOrder.setPayStatus(PayEnum.PayStatus.PAID.getCode());
                            int i = payService.payOrderStatusChange(payOrder);
                            if (i == 1) {
                                // 修改用户账户金额
                                PayManager.accountModify(StringHandler.getLong(payOrder.getBusyId()), PayEnum.AccountFlowType.TYPE_RECHARGE,
                                        payOrder.getAmount(),
                                        payOrder.getPayType().equals(PayEnum.payMentType.BANK.getCode()) ? String.format("余额充值-来自%s(%s)", payOrder.getBankName(), payOrder.getCardNo().substring(payOrder.getCardNo().length() - 4)) : "余额充值-来自支付宝",1);
                            }
                        }
                        break;
                    case "09":
                        //待支付不做处理
                        break;
                    case "02":
                    case "08":
                    case "-1":
                        //支付失败处理
                        if (payOrder.getBusinessType() == 1) {
                            String key = UserKey.rechargeCreateKey(payOrder.getDayKey(), payOrder.getBusyId());
                            String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                            String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                            Redis.key.increment(key, -1);
                            Redis.str.incr(zfbMoneyAllKey, -payOrder.getAmount());
                            Redis.str.incr(moneyAllKey, -payOrder.getAmount());
                        }
//                        payOrder.setPayStatus(PayEnum.PayStatus.FAIL.getCode());
//                        payService.payOrderStatusChange(payOrder);
                        orderService.orderTimeOut(StringHandler.getString(payOrder.getOrderId()));
                        break;
                }
            }catch (Exception e){
                Logger.error("订单超时处理异常,订单号："+payOrder.getOrderNo(),e);
            }
        });
    }
}
